package com.test.servlet;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import com.test.util.RSAEncrypt;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * Created by sun on 2016/11/11.
 */
@WebServlet(name = "ToLogin", urlPatterns = "/toLogin")
public class ToLogin extends HttpServlet {
    String path = "C:/tmp";

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();

        Map<String, String[]> params = request.getParameterMap();
        String restr = null;
        try {
            byte[] res = RSAEncrypt.decrypt(RSAEncrypt.loadPrivateKeyByStr(RSAEncrypt.loadPrivateKeyByFile(path)), Base64.decode(params.get("data")[0]));
            restr = new String(res);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if ("123456".equals(restr)) {
            out.write("{'success':true}");
        } else {
            out.write("{'success':false}");
        }
        out.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //生成秘钥

        RSAEncrypt.genKeyPairBySystem(path);
        try {
            request.setAttribute("publicKey", RSAEncrypt.loadPublicKeyByFile(path));
        } catch (Exception e) {
            e.printStackTrace();
        }
        request.getRequestDispatcher("/jsp/login.jsp").forward(request, response);
    }
}
